#!/bin/bash
#@pyfree 2020-04-16,py8105@163.com
#创建程序目录
#run for root
#定义程序全局路径变量
#程序根目录
dir='/usr/local/sysmgr'
curdir=$(pwd)

if [ ! -d $dir ]; then
    mkdir -p $dir
fi
#
echo "appdir="$dir
echo "curdir="$curdir
#复制程序文件到程序目录
/bin/cp -f {pyfree-sysmgr,SWL,*.xml} $dir
#
ls $dir
#
if [ ! -f "$dir/sysmgrStart.sh" ];then
#创建程序启动脚本sysmgr
cat > $dir/sysmgrStart.sh << eof
#!/bin/bash
pid=\`ps -ef | grep "pyfree-sysmgr*" | grep -v "grep" | wc -l\`
if [ \$pid -eq 0 ];then
    cd $dir
	echo "The sysmgr server will be start"
    nohup ./pyfree-sysmgr & > /dev/null
else
    echo "The sysmgr server is alreadly running"
fi 
eof
fi

if [ ! -f "$dir/sysmgrStop.sh" ];then
#创建程序关闭脚本sysmgr
cat > $dir/sysmgrStop.sh << eof
#!/bin/bash
pid=\`ps -ef | grep "pyfree-sysmgr*" | grep -v "grep" | wc -l\`
if [ \$pid -ne 0 ];then
	echo "The sysmgr server will be stop"
    killall -9 pyfree-sysmgr
else
	echo "The sysmgr server is stoping, don't stop it"
fi 
eof
fi

#给服务启动脚本添加执行权限
chmod o+x $dir/{sysmgrStart.sh,sysmgrStop.sh}

if [ ! -f "/usr/lib/systemd/system/pyfreeMgr.service" ];then
#创建程序启动文件到centos7服务启动路径/usr/lib/systemd/system
cat > /usr/lib/systemd/system/pyfreeMgr.service <<eof
[Unit]
Description=pyfree-sysmgr
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=$dir/sysmgrStart.sh
ExecReload=
ExecStop=$dir/sysmgrStop.sh
PrivateTmp=true
[Install]
WantedBy=multi-user.target
eof
fi

#给sysmgr生成liscense文件sn.txt, 如果是32位系统，修改为SWL_x32.exe 
#0表示网卡，1表示磁盘； 22表示生成sn.txt文件，这里选择网卡，生成sn.txt liscense文件
cd $dir
./SWL 0 22
cd $curdir

#设置开机启动gather服务
systemctl daemon-reload
chmod o-x /usr/lib/systemd/system/pyfreeMgr.service
systemctl enable pyfreeMgr.service
#查看服务是否开机启动：
#systemctl is-enabled pyfreeMgr.service
#设置开机时禁用服务
#systemctl disable pyfreeMgr.service
#启动服务
#systemctl start pyfreeMgr.service

#停止服务
#systemctl stop pyfreeMgr.service

